package test13;
import java.lang.Cloneable;//导入Cloneable接口
//继承接口
class Person implements Cloneable {
    String name;
    int age;
    Address address;

    public Person(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person cloned = (Person) super.clone();
        cloned.address = (Address) address.clone(); // 手动克隆引用类型字段
        return cloned;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + ", address=" + address + '}';
    }
}

class Address implements Cloneable {
    String city;
    String street;

    public Address(String city, String street) {
        this.city = city;
        this.street = street;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // Address 的 clone() 方法
    }

    @Override
    public String toString() {
        return "Address{city='" + city + "', street='" + street + "'}";
    }
}

public class Test11 {
    public static void main(String[] args) {
        try {
            Address address = new Address("Beijing", "Chang'an Street");
            Person person1 = new Person("Alice", 30, address);

            // 克隆 person1
            Person person2 = (Person) person1.clone();

            System.out.println("Original: " + person1);
            System.out.println("Cloned: " + person2);

            // 修改克隆对象的引用类型字段
            person2.address.city = "Shanghai";

            System.out.println("After modification - Original: " + person1);
            System.out.println("After modification - Cloned: " + person2);

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
